package com.hhm.huo.controller;


import cn.hutool.json.JSONUtil;
import com.hhm.huo.entity.Result;
import com.hhm.huo.entity.User;
import com.hhm.huo.service.IAuthorityService;
import com.hhm.huo.service.IUserService;
import com.hhm.huo.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 安安
 * @since 2022-06-06
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService userService;

    @Autowired
    IAuthorityService authorityService;

    @Autowired
    AuthenticationManager authenticationManager;

    @RequestMapping("mylogin")
    public Result mylogin(@RequestBody User user) {
        // 生成spring_security
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        try {
            Authentication authentication = authenticationManager.authenticate(token);
            // 获取登录用户信息
            User loginUser = (User)authentication.getPrincipal();
            // 生成jwt
            String token1 = JwtUtils.createToken(loginUser.getUsername(), 30, JSONUtil.toJsonStr(loginUser));
            // token1 传递到前端
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", token1);
            map.put("userInfo", loginUser);

            return new Result(200, "登录成功", map);
        }catch (Exception e) {
            System.out.println("异常--"+e);
            return new Result(100, "", e);
        }
    }

}
